from flask import render_template, flash, redirect, url_for, request
from . import bp_user
from .forms import Login_Form, Register_Form
from exts import mongo, loginmanager
from flask_login import login_user, current_user, logout_user
from werkzeug.security import generate_password_hash
from .models import Temp, verify_password
from bson.objectid import ObjectId

loginmanager.login_view = 'bp_user.login_user'
loginmanager.session_protection = 'strong'


@loginmanager.user_loader
def load_user(user_id):
    # 返回用户的id，这里是通过调用Temp类来返回一个id
    user = mongo.db.users.find_one({'_id': ObjectId(user_id)})
    return Temp(id=user.get('_id'), username=user.get('name'), email=user.get('email'),
                password=user.get('password'))


@bp_user.route('/login/', methods=['GET', 'POST'])
def login():
    login_form = Login_Form()
    if login_form.validate_on_submit():
        user = mongo.db.users.find_one(
            {'email': login_form.email.data})
        if user is not None and verify_password(user.get('password'), login_form.password.data):
            user = Temp(id=user.get('_id'), username=user.get('username'), email=user.get('email'),
                        password=user.get('password'))
            login_user(user)
            print(current_user)
            flash(u'登陆成功')
        flash(u'登陆失败')
        redirect(request.args.get('next') or url_for('bp_post.blog_index'))
    return render_template('login.html', form=login_form)


@bp_user.route('/register/', methods=['GET', 'POST'])
def register_user():
    reg_form = Register_Form()
    if reg_form.validate_on_submit():
        if mongo.db.users.find_one({'email': reg_form.email.data}):
            flash(u'邮箱地址已存在')
        else:
            mongo.db.users.insert_one({'username': reg_form.username.data,
                                       'password': generate_password_hash(reg_form.password.data),
                                       'email': reg_form.email.data})
        flash(u'注册成功')
    return render_template('register.html', form=reg_form)


@bp_user.route('/logout/', methods=['POST', 'GET'])
def logout():
    logout_user()
    return redirect(url_for('bp_post.blog_index'))
